from fastapi import APIRouter
from starlette.exceptions import HTTPException

from apps.employee.schemas import DpetIn
from apps.employee.models import Dept

deptRouter = APIRouter()

@deptRouter.get('/')
async def getDepts():
    dept_list = await Dept.all()
    return dept_list

@deptRouter.get('/{dept_id}')
async def getDept(dept_id: int):
    """根据Id获取部门名称"""
    dept = await Dept.get(id=dept_id)
    return dept

@deptRouter.post('/dept')
async def addDept(dept:DpetIn):
    # 部门名称不能重复
    existing_deptName = await Dept.filter(name = dept.name)
    if existing_deptName:
        raise HTTPException(status_code=423, detail="该部门已经存在")
    # 办公地址不能重复
    existing_local = await Dept.filter(local = dept.local)
    if existing_local:
        raise HTTPException(status_code=424, detail="该办公室已经被占用")

    # 创建新部门
    dept = await Dept.create(name = dept.name, local = dept.local)
    return {
        'status_code':200,
        'detail':'注册成功'
    }


@deptRouter.delete('/{dept_id}')
async def deleteDept(dept_id:int):
    rows = await Dept.filter(id = dept_id).delete()
    if rows == 0:
        raise HTTPException(status_code=404, detail="您要删除的数据没有找到")
    else:
        return {
            'status_code':200,
            'detail':'删除成功'
        }

@deptRouter.put('/{dept_id}')
async def updateDept(dept_id:int, dept:DpetIn):
    # 把接收到的dept 由对象转换成字典
    dept_data = dept.model_dump()
    await Dept.filter(id = dept_id).update(**dept_data)

    return {
        'status_code':200,
        'detail':'修改成功'
    }

